package edu.xmu.software.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.xmu.software.dao.ItemDAO;
import edu.xmu.software.pojo.Item;

public class ItemAddController extends SimpleFormController  {

	private ItemDAO itemDAO;

	public void setItemDAO(ItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}

	
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors){
		Item it = (Item) command;
		
		String editor = (String) request.getSession().getAttribute("userName");
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date date = new java.util.Date();
		String time = format.format(date);
		it.setEditor(editor);
		it.setEditTime(time);
		boolean success = itemDAO.addNewItem(it);
		if (success) {
			return new ModelAndView("addsucess");
		}
		else
			try {
				response.sendRedirect("userRedirect.do?action=upload&error=1");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;	
	}	
}
